package com.gss.plugin.kafka.config;

import org.apache.kafka.clients.CommonClientConfigs;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.common.config.SaslConfigs;
import org.apache.kafka.common.serialization.StringSerializer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.annotation.EnableKafka;
import org.springframework.kafka.core.DefaultKafkaProducerFactory;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.core.ProducerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * @author: DYang
 * @since: 2023/8/24
 * @description: 生产者配置
 */
@ConditionalOnProperty(name = "stars.kafka.producer.enable",havingValue = "true")
@Configuration
@EnableKafka
public class KafkaProducerConfig {

    @Autowired
    private KafkaProperties kafkaProperties;

    public Map<String, Object> producerConfigs() {
        KafkaProperties.ProducerConfig producerConfig = kafkaProperties.getProducer();
        Map<String, Object> props = new HashMap<>();
        props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, kafkaProperties.getServers());
        props.put(ProducerConfig.RETRIES_CONFIG, producerConfig.getRetries());
        props.put(ProducerConfig.BATCH_SIZE_CONFIG, producerConfig.getBatchSize());
        props.put(ProducerConfig.BUFFER_MEMORY_CONFIG, producerConfig.getBufferMemory());
        props.put(ProducerConfig.MAX_REQUEST_SIZE_CONFIG, producerConfig.getMaxRequestSize());
        props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);

        props.put(ProducerConfig.ACKS_CONFIG, producerConfig.getAck());

        //安全认证
        if (kafkaProperties.isSecurityEnable()) {
            //配置security.protocol
            props.put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, kafkaProperties.getSecurityProtocol());
            //配置sasl.mechanism
            props.put(SaslConfigs.SASL_MECHANISM, kafkaProperties.getSaslMechanism());
            //配置sasl.jaas.config
            props.put(SaslConfigs.SASL_JAAS_CONFIG, kafkaProperties.getSaslJaasConfig());
        }
        return props;
    }

    public ProducerFactory<String, String> producerFactory() {
        return new DefaultKafkaProducerFactory<>(producerConfigs());
    }

    @Bean
    public KafkaTemplate<String, String> kafkaTemplate() {
        return new KafkaTemplate<String, String>(producerFactory());
    }

}
